﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JzSport.Model
{
    public class MessageRepository : IMessageRepository
    {
        private JzSportDbContext _dbContext;

        public MessageRepository(JzSportDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public bool Create(Message message)
        {
            _dbContext.Set<Message>().Add(message);
            return false;
        }

        public Message Get(Guid id)
        {
            return _dbContext.Set<Message>().Where(p => p.Id == id).SingleOrDefault();
        }

        public List<Data.MessageView> GetList(Guid clipId)
        {
            return _dbContext.Set<Data.MessageView>().Where(p => p.MessageClipId == clipId && p.IsDeleted == false)
                .OrderBy(p => p.CreatedTime)
                .ToList();
        }

        public void Update(Message message)
        {
            _dbContext.Entry<Message>(message).State = System.Data.EntityState.Modified;
        }

        public void Delete(Message message)
        {
            _dbContext.Entry<Message>(message).State = System.Data.EntityState.Deleted;
        }

        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="messageClipId"></param>
        public void DeleteByClip(Guid messageClipId)
        {
            List<Message> messageList = _dbContext.Set<Message>().Where(p => p.MessageClipId == messageClipId).ToList();
            for (int index = 0; index < messageList.Count; index++)
            {
                messageList[index].IsDeleted = true;
                _dbContext.Entry<Message>(messageList[index]).State = System.Data.EntityState.Modified;
            }
        }
    }
}
